package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"promsync/progress/log"

	"github.com/nacos-group/nacos-sdk-go/model"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"promsync/cmd/config"
	"promsync/progress/path"
)

var (
	syncNacosClient config_client.IConfigClient
)

type Client struct {
}

func InitClient(config *config.AppConfig) error {
	//create ServerConfig
	sc := []constant.ServerConfig{
		*constant.NewServerConfig(config.Nacos.Server, config.Nacos.Port, constant.WithContextPath(config.Nacos.Path),
			constant.WithScheme("http")),
	}

	dir := path.GetCurrentDir()
	//create ClientConfig
	cc := *constant.NewClientConfig(
		constant.WithNamespaceId(config.Nacos.Namespace),
		constant.WithTimeoutMs(30000),
		constant.WithUsername(config.Nacos.Username),
		constant.WithPassword(config.Nacos.Password),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir(dir+"/logs/nacos"),
		constant.WithCacheDir(dir+"/cache"),
		constant.WithLogLevel("info"),
		constant.WithCustomLogger(log.Log),
	)

	// create config client
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
	if err != nil {
		return err
	}
	syncNacosClient = client
	return nil
}

func GetConfigList(group string) ([]model.ConfigItem, error) {
	result, err := syncNacosClient.SearchConfig(vo.SearchConfigParam{
		Search:   "blur",
		Group:    group,
		PageNo:   1,
		PageSize: 10000,
	})

	if err != nil {
		return nil, err
	}
	return result.PageItems, nil
}

func ListenerConfig(group string, dataId string, content string, ch chan string) error {
	err := syncNacosClient.ListenConfig(vo.ConfigParam{
		DataId:  dataId,
		Group:   group,
		Content: content,
		OnChange: func(namespace, group, dataId, data string) {
			ch <- data
		},
	})
	return err
}

func RemoveListenerConfig(config model.ConfigItem) error {
	err := syncNacosClient.CancelListenConfig(vo.ConfigParam{
		DataId:  config.DataId,
		Group:   config.Group,
		Content: config.Content,
	})
	return err
}

func GetConfig(group string, dataId string) (string, error) {
	configStr, err := syncNacosClient.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
	})
	return configStr, err
}

func CreateConfig(group string, dataId string, content string) (bool, error) {
	success, err := syncNacosClient.PublishConfig(vo.ConfigParam{
		DataId:  dataId,
		Group:   group,
		Content: content,
	})
	return success, err
}
